import axios, { type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'

// 创建axios实例
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加管理员token
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 统一处理后端返回的数据格式
    if (data && typeof data === 'object') {
      if (data.success === false) {
        ElMessage.error(data.message || '请求失败')
        return Promise.reject(new Error(data.message || '请求失败'))
      }
      
      return data
    }
    
    return data
  },
  (error) => {
    console.error('API请求错误:', error)
    
    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage.error('未授权，请重新登录')
          localStorage.removeItem('admin_token')
          window.location.href = '/admin/login'
          break
        case 403:
          ElMessage.error('拒绝访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 通用API请求方法
export const api = {
  // GET请求
  get<T = any>(url: string, params?: any): Promise<T> {
    return request.get(url, { params })
  },

  // POST请求
  post<T = any>(url: string, data?: any): Promise<T> {
    return request.post(url, data)
  },

  // PUT请求
  put<T = any>(url: string, data?: any): Promise<T> {
    return request.put(url, data)
  },

  // DELETE请求
  delete<T = any>(url: string): Promise<T> {
    return request.delete(url)
  }
}

// ==================== 管理员相关API ====================

// 管理员登录
export const adminLogin = (username: string, password: string) => {
  return api.post('/api/admin/login', { username, password })
}

// 获取管理员信息
export const getAdminInfo = () => {
  return api.get('/api/admin/info')
}

// 获取仪表盘统计数据
export const getDashboardStats = () => {
  return api.get('/api/admin/dashboard/stats')
}

// ==================== 用户管理API ====================

// 获取用户列表
export const getUserList = (params: any) => {
  return api.get('/api/admin/users', params)
}

// 获取用户详情
export const getUserDetail = (userId: number) => {
  return api.get(`/api/admin/users/${userId}`)
}

// 更新用户积分
export const updateUserCredits = (userId: number, data: any) => {
  return api.post(`/api/admin/users/${userId}/credits`, data)
}

// 设置用户VIP
export const setUserVip = (userId: number, data: any) => {
  return api.post(`/api/admin/users/${userId}/vip`, data)
}

// 封禁/解封用户
export const updateUserStatus = (userId: number, status: string) => {
  return api.put(`/api/admin/users/${userId}/status`, { status })
}

// ==================== 积分管理API ====================

// 获取积分统计
export const getCreditsStats = () => {
  return api.get('/api/admin/credits/stats')
}

// 获取积分套餐列表
export const getCreditsPackages = () => {
  console.log('🚀 [API调试] 调用管理端积分套餐API: /api/admin/credits/packages')
  console.log('🚀 [API调试] API baseURL:', API_BASE_URL)
  console.log('🚀 [API调试] 完整URL路径:', API_BASE_URL + '/api/admin/credits/packages')
  
  // 添加请求拦截器来监控实际发送的请求
  const request = api.get('/api/admin/credits/packages')
  
  // 监控请求
  request.then(response => {
    console.log('📈 [API调试] 请求成功')
    console.log('📈 [API调试] 响应数据:', response)
  }).catch(error => {
    console.error('📉 [API调试] 请求失败:', error)
  })
  
  return request
}

// 创建积分套餐
export const createCreditsPackage = (data: any) => {
  return api.post('/api/admin/credits/packages', data)
}

// 更新积分套餐
export const updateCreditsPackage = (id: number, data: any) => {
  return api.put(`/api/admin/credits/packages/${id}`, data)
}

// 删除积分套餐
export const deleteCreditsPackage = (id: number) => {
  return api.delete(`/api/admin/credits/packages/${id}`)
}

// 获取积分交易记录
export const getCreditsTransactions = (params: any) => {
  return api.get('/api/admin/credits/transactions', params)
}

// 获取积分消耗规则
export const getCreditsRules = () => {
  return api.get('/api/admin/credits/rules')
}

// 更新积分消耗规则
export const updateCreditsRule = (id: number, data: any) => {
  return api.put(`/api/admin/credits/rules/${id}`, data)
}

// 更新积分套餐状态
export const updateCreditsPackageStatus = (id: number, status: number) => {
  return api.put(`/api/admin/credits/packages/${id}/status`, { status })
}

// 创建积分消耗规则
export const createCreditsRule = (data: any) => {
  return api.post('/api/admin/credits/rules', data)
}

// 删除积分消耗规则
export const deleteCreditsRule = (id: number) => {
  return api.delete(`/api/admin/credits/rules/${id}`)
}

// 更新积分消耗规则状态
export const updateCreditsRuleStatus = (id: number, status: number) => {
  return api.put(`/api/admin/credits/rules/${id}/status`, { status })
}

// 同步积分套餐到小程序数据库
export const syncCreditsPackagesToMiniProgram = () => {
  return api.post('/api/admin/credits/packages/sync')
}

// 同步积分消耗规则到小程序数据库
export const syncCreditsRulesToMiniProgram = () => {
  return api.post('/api/admin/credits/rules/sync')
}

// ==================== 订单管理API ====================

// 获取订单统计
export const getOrderStats = () => {
  return api.get('/api/admin/orders/stats')
}

// 获取订单列表
export const getOrderList = (params: any) => {
  return api.get('/api/admin/orders', params)
}

// 获取订单详情
export const getOrderDetail = (orderId: string) => {
  return api.get(`/api/admin/orders/${orderId}`)
}

// 取消订单
export const cancelOrder = (orderId: string) => {
  return api.put(`/api/admin/orders/${orderId}/cancel`)
}

// 退款订单
export const refundOrder = (orderId: string, data?: any) => {
  return api.put(`/api/admin/orders/${orderId}/refund`, data)
}

// ==================== AI生图统计API ====================

// 获取AI生图统计
export const getAiImageStats = () => {
  return api.get('/api/admin/ai-image/stats')
}

// 获取AI生图历史记录
export const getAiImageHistory = (params: any) => {
  return api.get('/api/admin/ai-image/history', params)
}

// 删除AI生图记录
export const deleteAiImageRecord = (recordId: string | number) => {
  return api.delete(`/api/admin/ai-image/history/${recordId}`)
}

// ==================== 用户作品管理API ====================

// 获取用户作品统计数据
export const getUserWorkStats = () => {
  return api.get('/api/admin/user-works/stats')
}

// 获取用户作品列表
export const getUserWorkList = (params: any) => {
  return api.get('/api/admin/user-works', params)
}

// 删除用户作品
export const deleteUserWork = (workId: string | number) => {
  return api.delete(`/api/admin/user-works/${workId}`)
}

// 更新用户作品状态
export const updateUserWorkStatus = (workId: string | number, status: number) => {
  return api.put(`/api/admin/user-works/${workId}/status`, { status })
}

// ==================== 系统管理API ====================

// 获取系统统计
export const getSystemStats = () => {
  return api.get('/api/admin/system/stats')
}

// 获取操作日志
export const getOperationLogs = (params: any) => {
  return api.get('/api/admin/system/logs', params)
}

// 清理操作日志
export const clearOperationLogs = (params?: { beforeDate?: string }) => {
  return api.delete('/api/admin/system/logs/clear')
}

// 获取系统信息
export const getSystemInfo = () => {
  return api.get('/api/admin/system/info')
}

// ==================== 个人信息管理接口 ====================

// 获取个人信息
export const getAdminProfile = () => {
  return api.get('/api/admin/profile')
}

// 更新个人信息
export const updateAdminProfile = (data: any) => {
  return api.put('/api/admin/profile', data)
}

// 修改密码
export const updateAdminPassword = (data: any) => {
  return api.put('/api/admin/profile/password', data)
}

// ==================== VIP管理API ====================

// 获取VIP统计数据
export const getVipStats = () => {
  return api.get('/api/admin/vip/stats')
}

// 获取VIP用户列表
export const getVipUsers = (params: any) => {
  return api.get('/api/admin/vip/users', params)
}

// 获取VIP用户详情
export const getVipUserDetail = (userId: number) => {
  return api.get(`/api/admin/vip/users/${userId}`)
}

// VIP用户续期
export const extendVipUser = (userId: number, data: any) => {
  return api.post(`/api/admin/vip/users/${userId}/extend`, data)
}

// 取消用户VIP
export const cancelUserVip = (userId: number, data?: any) => {
  return api.post(`/api/admin/vip/users/${userId}/cancel`, data)
}

// 获取VIP套餐列表
export const getVipPackages = () => {
  return api.get('/api/admin/vip/packages')
}

// 创建VIP套餐
export const createVipPackage = (data: any) => {
  return api.post('/api/admin/vip/packages', data)
}

// 更新VIP套餐
export const updateVipPackage = (id: number, data: any) => {
  return api.put(`/api/admin/vip/packages/${id}`, data)
}

// 删除VIP套餐
export const deleteVipPackage = (id: number) => {
  return api.delete(`/api/admin/vip/packages/${id}`)
}

// 更新VIP套餐状态
export const updateVipPackageStatus = (id: number, status: number) => {
  return api.put(`/api/admin/vip/packages/${id}/status`, { status })
}

// 获取VIP订单列表
export const getVipOrders = (params: any) => {
  return api.get('/api/admin/vip/orders', params)
}

// 获取VIP订单详情
export const getVipOrderDetail = (orderId: string) => {
  return api.get(`/api/admin/vip/orders/${orderId}`)
}

// VIP订单退款
export const refundVipOrder = (orderId: string, data?: any) => {
  return api.post(`/api/admin/vip/orders/${orderId}/refund`, data)
}

export default api
